import PropTypes from 'prop-types';
import React from 'react';
import { animated, config as SpringConfig, Spring } from 'react-spring';

import classNames from 'classnames';

export interface ICollapseProps {
  className?: string;
  style?: React.CSSProperties;
  active?: boolean;
  delay?: number;
  config?: string;
  onStart?: () => void;
  onRest?: () => void;
}

interface ICollapseConfig {
  [key: string]: any;
}

export class Collapse extends React.PureComponent<ICollapseProps, {}> {
  public static propTypes = {
    className: PropTypes.string,
    style: PropTypes.object,
    active: PropTypes.bool,
    delay: PropTypes.number,
    config: PropTypes.oneOf(['default', 'wobbly', 'stiff', 'slow', 'molasses']),
    onStart: PropTypes.func,
    onRest: PropTypes.func,
  };

  public static defaultProps = {
    className: '',
    style: null,
    active: false,
    delay: 0,
    config: 'default',
  };

  public render() {
    const { className, style, active, onStart, onRest, delay, config } = this.props;
    let from = {
      height: 0,
      opacity: 0,
    };
    let to = {
      height: 'auto',
      opacity: 1,
    };
    let collapseConfig: ICollapseConfig = SpringConfig;
    return (
      <Spring
        native
        onStart={onStart}
        onRest={onRest}
        delay={delay}
        from={active ? from : to}
        to={active ? to : from}
        config={{
          ...collapseConfig[`${config}`],
        }}>
        {
          (styles) =>
            <animated.div style={{ ...styles, overflow: 'hidden' }}>
              <div className={classNames('br-collapse', className)} style={style}>
                {this.props.children}
              </div>
            </animated.div>
        }
      </Spring>
    );
  }
}
